package com.sinba.common.business.service;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Map;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.sinba.common.business.dao.IBuyDAO;
import com.sinba.common.business.dao.IMatchDAO;
import com.sinba.common.business.dao.ISellDAO;
import com.sinba.common.business.dto.CurrentSaleDTO;
import com.sinba.common.business.dto.MatchDTO;
import com.sinba.common.business.dto.MatchGridDTO;
import com.sinba.common.business.dto.MatchQueryDTO;
import com.sinba.common.business.dto.SellDTO;
import com.sinba.common.business.dto.SellQueryDTO;
import com.sinba.common.business.entity.Buy;
import com.sinba.common.business.entity.Match;
import com.sinba.common.business.entity.Sell;
import com.sinba.common.dto.PageDTO;
import com.sinba.common.exception.ApplicationException;
import com.sinba.common.sms.HttpSender;
import com.sinba.common.system.dao.IRuleDAO;
import com.sinba.common.system.dto.RuleDTO;
import com.sinba.common.system.entity.Rule;
import com.sinba.common.system.entity.TransactionRecord;
import com.sinba.common.system.service.IEmailService;
import com.sinba.common.system.service.IRuleService;
import com.sinba.common.system.service.ITransactionRecordService;
import com.sinba.common.user.dao.IRegisterUserDAO;
import com.sinba.common.user.dto.RegisterUserQueryDTO;
import com.sinba.common.user.entity.RegisterUser;
import com.sinba.common.user.service.IBonusService;
import com.sinba.common.utils.DoubleFormat;
import com.sinba.common.utils.TranType;

public class MatchService implements IMatchService {
	private static Logger logger = Logger.getLogger(MatchService.class);
	@Autowired
	private IMatchDAO matchDAO;
	@Autowired
	private IBuyDAO buyDAO;
	@Autowired
	private ISellDAO sellDAO;
	@Autowired
	private IRegisterUserDAO registerUserDAO;
	@Autowired
	private IBonusService bonusService;
	@Autowired
	private IRuleService ruleService;
	@Autowired
	private ITransactionRecordService transactionRecordService;
	@Autowired
	private IEmailService emailService;
	@Autowired
	private ISellService sellService;
	@Autowired
	private IRuleDAO ruleDAO;
	private String[] supportExtention = new String[]{"jpeg","jpg","bmp","png","JPEG","JPG","BMP","PNG"};
	
	
	@Transactional
	public String satrtMatch() {
		
		// TODO Auto-generated method stub
		StringBuffer sb = new StringBuffer();
		sb.append(">>>>>>>>>>>>>>>>>>>>开始\r\n");
		
		/*sb.append(timeoutPay());
		
		sb.append(timeoutConfirm());
		
		sb.append(accoutCheck());*/
		
		//找出买入
		Buy buy =buyDAO.findTop1BuyOrder();
		if(buy==null){
			sb.append("未找到援助别人订单\r\n");
			return sb.toString();
		}else{
			sb.append("正在匹配援助别人订单：编号： "+buy.getBuyUser()+",总金额:"+buy.getBuyMoney()+",剩余匹配金额:"+buy.getSurplusMoney()+"\r\n");
		}
		
		//找出卖出
		Sell sell = sellDAO.findTop1SellOrder();
		if(sell == null){
			sb.append("未找到被别人援助订单\r\n");
			return sb.toString();
		}else{
			sb.append("正在匹配被别人援助订单：编号： "+sell.getSellUser()+",总金额:"+sell.getSellMoney()+",剩余匹配金额:"+sell.getSurplusMoney()+"\r\n");
		}
		
		if(buy.getBuyUser().equals(sell.getSellUser())){
			sb.append("系统匹配提供援助与接受援助是同一个账号，请在后台调整一下优先级再重新匹配!\r\n");
			return sb.toString();
		}
		//本次买入金额
		Long buyMoney = buy.getSurplusMoney();
		
		//本次卖出金额
		Long sellMoney = sell.getSurplusMoney();
		
		//本次交易金额
		Long tranMoney = sellMoney; 
		if(buyMoney<sellMoney){
			tranMoney = buyMoney;
		}
		sb.append("匹配成功，本单匹配金额为： "+tranMoney+"\r\n");
		//生成一条匹配记录
		Match match = new Match();
		match.setBuy(buy);
		match.setSell(sell);
		match.setStatus(0);
		match.setMatchMoney(tranMoney);
		matchDAO.merge(match);
		//更新卖出账户
		buy.setSurplusMoney(buy.getSurplusMoney()-tranMoney);
		buy.setStatus(1);
		buy.setMatchTime(new Date());
		buyDAO.merge(buy);
		
		//更新买入账户账户
		sell.setSurplusMoney(sell.getSurplusMoney()-tranMoney);
		sell.setStatus(1);
		sell.setMatchTime(new Date());
		sellDAO.merge(sell);
		
		//邮件通知
		final String buyUser = buy.getBuyUser();
		final String sellUser = sell.getSellUser();
		final Long tempTranMoney = tranMoney;
		new Thread(new Runnable() {
			public void run() {
				emailService.sendMail(buyUser, "提供援助匹配成功-CHINA-ZOPA（中国版）", "恭喜您的用户在CHINA-ZOPA（中国版）中匹配成功！本次成功匹配金额："+tempTranMoney);
				emailService.sendMail(sellUser, "得到援助匹配成功-CHINA-ZOPA（中国版）", "恭喜您的用户在CHINA-ZOPA（中国版）中匹配成功！本次成功匹配金额：："+tempTranMoney);
			}
		}).start();
		
		sb.append(">>>>>>>>>>>>>>>>>>>>结束\r\n");
		return sb.toString();
	}
	
	
	@Transactional
	public synchronized String satrtMatchByGuPiao() {
		// TODO Auto-generated method stub
		RuleDTO ruleDTO = ruleService.findRuleInfo();
		
		
		StringBuffer sb = new StringBuffer();
		sb.append(">>>>>>>>>>>>>>>>>>>>开始\r\n<br>");
		
		
		//涨停或休市都不允许匹配
		if("Limit".equals(ruleDTO.getMarketStatus()) || "Rest".equals(ruleDTO.getMarketStatus())){
			sb.append("涨停或休市中，不允许匹配.......\r\n<br>");
			return sb.toString();
		}
		
		/*sb.append(timeoutPay());
		
		sb.append(timeoutConfirm());
		
		sb.append(accoutCheck());*/
		
		//找出买入
		Buy buy =buyDAO.findTop1BuyOrder();
		if(buy==null){
			sb.append("未找到买入排队\r\n<br>");
			return sb.toString();
		}else{
			sb.append("正在匹配买入排队订单：编号： "+buy.getBuyUser()+",总金额:"+buy.getdBuyMoney()+",剩余匹配金额:"+buy.getdSurplusMoney()+"\r\n<br>");
		}
		
		//找出卖出
		Sell sell = sellDAO.findTop1SellOrder();
		if(sell == null){
			sb.append("未找到卖出订单\r\n<br>");
			return sb.toString();
		}else{
			if(sell.getSellPrice()>ruleDTO.getAllowSellPrice()){
				return sb.append("最大允许卖出股价是："+ruleDTO.getAllowSellPrice().toString()+",当前股价是："+sell.getSellPrice()+"\r\n").toString();
			}
			sb.append("正在匹配卖出订单：编号： "+sell.getSellUser()+",总股数:"+sell.getSellMoney()+",单价:"+sell.getSellPrice()+",剩余匹配股数:"+sell.getSurplusMoney()+"\r\n<br>");
		}
		
		if(buy.getBuyUser().equals(sell.getSellUser())){
			sb.append("系统匹配卖出与买入是同一个账号，请在后台调整一下优先级再重新匹配!\r\n<br>");
			return sb.toString();
		}
		//本次买入金额
		Double dBuyMoney = DoubleFormat.format(buy.getdSurplusMoney());
		
		//本次卖出股数
		Long sellMoney = sell.getSurplusMoney();
		
		//卖出股数*价格=金额
		Double dSellMoney = DoubleFormat.format(sellMoney*sell.getSellPrice());
		sb.append("卖出股数*价格=金额="+dSellMoney+"\r\n<br>");
		
		//本次交易金额
		Double tranMoney = dSellMoney; 
		
		//如果本次买入可以全部买完
		if(dBuyMoney<dSellMoney){
			tranMoney = dBuyMoney;
		}
		
		sb.append("本次交易金额="+tranMoney+"\r\n<br>");
		sb.append("更新买入账--开始\r\n<br>");
		//------------买入账户--------------
		//更新买入账户
		buy.setdSurplusMoney(DoubleFormat.format(buy.getdSurplusMoney()-tranMoney));
		if(dBuyMoney<dSellMoney){
			buy.setStatus(2);
		}else{
			buy.setStatus(1);
		}
		
		buy.setMatchTime(new Date());
		buyDAO.merge(buy);
		
		//将股数拆分成3分挂牌卖出
		//本次将买股数是
		Double temp1 =DoubleFormat.format(tranMoney/sell.getSellPrice());
		sb.append("本次交易股数(Double)="+temp1+"\r\n<br>");
		Long gs = temp1.longValue();
		sb.append("本次交易股数="+gs+"\r\n<br>");
		if(gs<3){
			//第一份
			Double price1 = DoubleFormat.format(((sell.getSellPrice()/3)+sell.getSellPrice())*1.1);
			SellQueryDTO queryDto1 = new SellQueryDTO();
			queryDto1.setRemark("第一轮");
			queryDto1.setSellPrice(price1);
			queryDto1.setStatus(0);
			queryDto1.setSellUser(buy.getBuyUser());
			PageDTO pagedto1 = sellDAO.findSellPage(queryDto1, "desc", "id");
			if(pagedto1.getTotalSize()==1){
				Sell sell1 = (Sell)pagedto1.getData().get(0);
				//System.out.println("合并前："+sell1.getSellMoney());
				sell1.setSellMoney(sell1.getSellMoney()+gs);
				sell1.setBuyGuShu(sell1.getBuyGuShu()+gs);
				sell1.setSurplusMoney(sell1.getSurplusMoney()+gs);
				sellDAO.merge(sell1);
				//System.out.println(buy.getBuyUser()+",第一轮"+","+price1+"合并,"+sell1.getSellMoney());
			}else{
				SellDTO sellDto1 = new SellDTO();
				sellDto1.setSellUser(buy.getBuyUser());
				sellDto1.setSellMoney(gs);
				sellDto1.setSellPrice(price1);
				sellDto1.setRemark("第一轮");
				sellDto1.setBuy(buy);
				sellDto1.setBuyPrice(sell.getSellPrice());
				sellDto1.setBuyGuShu(gs);
				sellDto1.setStatus(0);
				sellService.save(sellDto1);
			}
		}else{
			Long average = gs/3;
			Long surplus = gs-(average*3);
			//第一份
			Double price1 = DoubleFormat.format(((sell.getSellPrice()/3)+sell.getSellPrice())*1.1);
			SellQueryDTO queryDto1 = new SellQueryDTO();
			queryDto1.setRemark("第一轮");
			queryDto1.setSellPrice(price1);
			queryDto1.setStatus(0);
			queryDto1.setSellUser(buy.getBuyUser());
			PageDTO pagedto1 = sellDAO.findSellPage(queryDto1, "desc", "id");
			if(pagedto1.getTotalSize()==1){
				Sell sell1 = (Sell)pagedto1.getData().get(0);
				//System.out.println("合并前："+sell1.getSellMoney());
				sell1.setSellMoney(sell1.getSellMoney()+average);
				sell1.setBuyGuShu(sell1.getBuyGuShu()+average);
				sell1.setSurplusMoney(sell1.getSurplusMoney()+average);
				sellDAO.merge(sell1);
				//System.out.println(buy.getBuyUser()+",第一轮"+","+price1+"合并,"+sell1.getSellMoney());
			}else{
				SellDTO sellDto1 = new SellDTO();
				sellDto1.setSellUser(buy.getBuyUser());
				sellDto1.setSellMoney(average);
				sellDto1.setSellPrice(price1);
				sellDto1.setRemark("第一轮");
				sellDto1.setBuy(buy);
				sellDto1.setBuyPrice(sell.getSellPrice());
				sellDto1.setBuyGuShu(average);
				sellDto1.setStatus(0);
				sellService.save(sellDto1);
			}
			
			
			//第二份
			Double price2 = DoubleFormat.format(((sell.getSellPrice()/3)+price1)*1.1);
			SellQueryDTO queryDto2 = new SellQueryDTO();
			queryDto2.setRemark("第二轮");
			queryDto2.setSellPrice(price2);
			queryDto2.setStatus(0);
			queryDto2.setSellUser(buy.getBuyUser());
			PageDTO pagedto2 = sellDAO.findSellPage(queryDto2, "desc", "id");
			if(pagedto2.getTotalSize()==1){
				Sell sell2 = (Sell)pagedto2.getData().get(0);
				//System.out.println("合并前："+sell2.getSellMoney());
				sell2.setSellMoney(sell2.getSellMoney()+average);
				sell2.setBuyGuShu(sell2.getBuyGuShu()+average);
				sell2.setSurplusMoney(sell2.getSurplusMoney()+average);
				sellDAO.merge(sell2);
				//System.out.println(buy.getBuyUser()+",第二轮"+","+price2+"合并,"+sell2.getSellMoney());
			}else{
				SellDTO sellDto2 = new SellDTO();
				sellDto2.setSellUser(buy.getBuyUser());
				sellDto2.setSellMoney(average);
				sellDto2.setSellPrice(price2);
				sellDto2.setRemark("第二轮");
				sellDto2.setBuy(buy);
				sellDto2.setBuyPrice(sell.getSellPrice());
				sellDto2.setBuyGuShu(average);
				sellDto2.setStatus(0);
				sellService.save(sellDto2);
			}
			//第三份
			Double price3 = DoubleFormat.format(((sell.getSellPrice()/3)+price2)*1.1);
			
			SellQueryDTO queryDto3 = new SellQueryDTO();
			queryDto3.setRemark("第三轮");
			queryDto3.setSellPrice(price3);
			queryDto3.setStatus(0);
			queryDto3.setSellUser(buy.getBuyUser());
			PageDTO pagedto3 = sellDAO.findSellPage(queryDto3, "desc", "id");
			
			if(surplus>=3){
				System.out.println("这里出现了一个平分不合理的："+sell.getId());
				logger.error("这里出现了一个平分不合理的："+sell.getId());
			}
			
			
			if(pagedto3.getTotalSize()==1){
				
				Sell sell3 = (Sell)pagedto3.getData().get(0);
				//System.out.println("合并前："+sell3.getSellMoney());
				sell3.setSellMoney(sell3.getSellMoney()+average+surplus);
				sell3.setBuyGuShu(sell3.getBuyGuShu()+average+surplus);
				sell3.setSurplusMoney(sell3.getSurplusMoney()+average+surplus);
				sellDAO.merge(sell3);
				//System.out.println(buy.getBuyUser()+",第三轮"+","+price3+"合并,"+average+surplus);
			}else{
				SellDTO sellDto3 = new SellDTO();
				sellDto3.setSellUser(buy.getBuyUser());
				sellDto3.setSellMoney(average+surplus);
				sellDto3.setSellPrice(price3);
				sellDto3.setRemark("第三轮");
				sellDto3.setBuy(buy);
				sellDto3.setBuyPrice(sell.getSellPrice());
				sellDto3.setBuyGuShu(average+surplus);
				sellDto3.setStatus(0);
				sellService.save(sellDto3);
			}
		}
		
		
		
		
		sb.append("更新买入账---结束\r\n<br>");
		
		
		
		sb.append("更新卖出账户---开始\r\n<br>");
		
		//更新卖出账户
		sell.setSurplusMoney(sell.getSurplusMoney()-gs);
		if(dBuyMoney>=dSellMoney && sell.getSurplusMoney()==0){
			sell.setStatus(2);
			//收取5%大盘费用
			Double dSellMoney1 = DoubleFormat.format(sell.getSellMoney()*sell.getSellPrice()*0.95);
			
			RegisterUser registerUser = registerUserDAO.findUniqueBy("loginName", sell.getSellUser());
			if(registerUser!=null){
				sb.append("70%回到账户\r\n<br>");
				//70%回到账户
				TransactionRecord t = new TransactionRecord();
				t.setLoginName(sell.getSellUser());
				t.setTransactionObject("system");
				t.setTransactionType(TranType.MaiChu);
				t.setRemark("70%回到账户");
				transactionRecordService.updateTran(t, TranType.STATIC, DoubleFormat.format(dSellMoney1*0.7), TranType.ADD);
			
				//30%回购
				sb.append("30%回购\r\n<br>");
				Buy buy30d = new Buy();
				buy30d.setBuyUser(sell.getSellUser());
				buy30d.setdBuyMoney(DoubleFormat.format(dSellMoney1*0.3));
				buy30d.setdSurplusMoney(DoubleFormat.format(dSellMoney1*0.3));
				buy30d.setPriority(999);
				buy30d.setStatus(0);
				buy30d.setRemark("30%回购");
				buyDAO.merge(buy30d);
				
				//卖出完成短信通知
				HttpSender.sendSms(registerUser.getMobile(), "温馨提示：编号"+registerUser.getLoginName()+"。股票已卖出。请登入账户选择提现或者回购。科百特（厦门）信息科技有限公司");
				
			}
		}else{
			sell.setStatus(1);
		}
		sell.setMatchTime(new Date());
		sellDAO.merge(sell);
		
		sb.append("更新卖出账户---结束\r\n<br>");
		
		sb.append(">>>>>>>>>>>>>>>>>>>>结束\r\n<br>");
		Long allSurplusMoney = sellDAO.allSurplusMoney();
		
		if(allSurplusMoney%ruleDTO.getRule020().longValue()!=0){
			logger.error("总股数出错了"+allSurplusMoney+",正在交易：卖出ID:"+sell.getId()+",买入ID:"+buy.getId());
			System.out.println("总股数出错了"+allSurplusMoney+",正在交易：卖出ID:"+sell.getId()+",买入ID:"+buy.getId());
			throw new ApplicationException("总股数出错了"+allSurplusMoney+",正在交易：卖出ID:"+sell.getId()+",买入ID:"+buy.getId());
		}
		
		return sb.toString();
	}

	@Transactional
	public PageDTO findMatchPage(MatchQueryDTO queryDTO, String sord,
			String sidx) {
		PageDTO pageDto = matchDAO.findMatchPage(queryDTO, sord, sidx);
		List<Match> lists = pageDto.getData();
		List<MatchGridDTO> dtos = new ArrayList<MatchGridDTO>();
		Set<String> loginNames = new HashSet<String>();
		for(Match match:lists){
			MatchGridDTO dto = new MatchGridDTO();
			MatchGridDTO.entity2dto(match, dto);
			dto.setBuyUser(match.getBuy().getBuyUser());
			dto.setSellUser(match.getSell().getSellUser());
			dto.setBuyMoney(match.getBuy().getBuyMoney());
			dto.setSellMoney(match.getSell().getSellMoney());
			if ( dto.getSellUser() != null ) { loginNames.add(dto.getSellUser()); }
			if ( dto.getBuyUser() != null ) { loginNames.add(dto.getBuyUser()); }
			dtos.add(dto);
		}
		if (loginNames.size() > 0) {
			Map<String, RegisterUser> users = registerUserDAO.findUserByLoginNames(loginNames.toArray(new String[loginNames.size()]));
			for (MatchGridDTO dto : dtos) {
				RegisterUser sellUser = null;//卖出人的信息
				if (dto.getSellUser() != null && (sellUser = users.get(dto.getSellUser())) != null) {
					dto.setSellUserName( sellUser.getUserName() );
					dto.setSellUserStatus( sellUser.getUserStatus());
					dto.setSellUserBankType( sellUser.getAccountType());
					dto.setSellUserBankAccount( sellUser.getBankAccount() );
					dto.setSellUserBankPhone( sellUser.getPhone() );
					dto.setSellUserBankQq( sellUser.getQq() );
				}
				RegisterUser buyUser = null;//购买人的信息
				if (dto.getBuyUser() != null && (buyUser = users.get(dto.getBuyUser())) != null) {
					dto.setBuyUserName( buyUser.getUserName() );
					dto.setBuyUserStatus( buyUser.getUserStatus());
					dto.setBuyUserBankType( buyUser.getAccountType());
					dto.setBuyUserBankAccount( buyUser.getBankAccount() );
					dto.setBuyUserBankPhone( buyUser.getPhone() );
					dto.setBuyUserBankQq( buyUser.getQq() );
				}
			}
		}
		pageDto.setData(dtos);
		return pageDto;
	}

	@Transactional
	public synchronized String payment(MatchDTO matchDTO,File file,String filename,String pathname) {
		if(file == null){
			return "凭证图片必须上传!";
		}
		Match match = matchDAO.findById(matchDTO.getId());
		if(match!=null && (match.getStatus()==0 ||  match.getStatus()==3)){
			if(chageExtention(filename, supportExtention)){
				String filepath = saveImg(file, pathname,match,filename);
				match.setImgUrl(filepath);
				match.setMessage(matchDTO.getMessage());
				match.setMessageTime(new Date());
				match.setStatus(1);
				matchDAO.merge(match);
				return "确认汇款操作成功!";
			}else{
				return "不支持的凭证图片格式!";
			}
		}else{
			return "确认汇款操作操作失败!";
		}
		
		
	}

	@Transactional
	public synchronized String confirmPay(MatchDTO matchDTO) {
		Match match = matchDAO.findById(matchDTO.getId());
		if(match!=null && match.getStatus() == 1){
			match.setStatus(2);
			match.setCloseTime(new Date());
			matchDAO.merge(match);
			return "收款确认操作成功!";
		}else{
			return "操作失败，该申请状态已经变更!";
		}
	}


	/**
	 * 保存图片
	 */
	@Transactional
	private String saveImg(File imgUrl,String pathname,Match match,String filename){
		Boolean flag = false;
		String destFilePath = deelPath(match,filename) ;
		File destFile = new File(pathname + destFilePath);
		try {
			FileUtils.copyFile(imgUrl, destFile );
			flag = true;
		} catch (IOException e) {
			throw new RuntimeException("保存图片出错");
		}
		return destFilePath;
	}
	/**
	 * 生成目标路径
	 */
	@Transactional
	private String deelPath(Match match,String filename){
		String extention = filename.substring(filename.lastIndexOf(".")+1);
		return "upload/"+match.getId()+new Random().nextInt(100)+new Date().getTime()+"."+extention;
	}
	/**
	 * 判断格式
	 * @return
	 */
	@Transactional
	private Boolean chageExtention(String filename,String[] extention){
		String ex = filename.substring(filename.lastIndexOf(".") + 1);
		for(String str : extention){
			if(str.equals(ex)){
				return true;
			}
		}
		return false;
	}

	@Transactional
	public MatchDTO findById(Long id) {
		if(id != null && id != 0){
			Match match = matchDAO.findById(id);
			MatchDTO dto = new MatchDTO();
			dto.setImgUrl(match.getImgUrl());
			dto.setId(match.getId());
			dto.setMessage(match.getMessage());
			dto.setStatus(match.getStatus());
			return dto;
		}
		return null;
	}
	
	@Transactional
	public synchronized void checkCompute(){
		MatchQueryDTO queryDTO = new MatchQueryDTO();
		queryDTO.setStatus(2);//交易成功
		queryDTO.setStart(0);
		queryDTO.setLimit(100);
		queryDTO.setSearchType(MatchQueryDTO.FindNoCalculat);
		PageDTO pageDto = matchDAO.findMatchPage(queryDTO, "asc", "closeTime");
		System.out.println(">>>>>>>>>>>>对已确认收款记录进行计算资金");
		//拿到匹配订单状态是交易成功的全部订单
		if(pageDto.getTotalSize()>0){
			RuleDTO ruleDTO = ruleService.findRuleInfo();
			List<Match> lists = (List<Match>)pageDto.getData();
			for(Match match:lists){
				//判断是否已全部确认
				if(isAllMatchConfirm(match.getBuy())){
					//1、修改Buy状态为2，交易成功
					Buy buy = match.getBuy();
					buy.setStatus(2);
					buyDAO.merge(buy);
					
					if(isAllMatchConfirm(match.getSell())){
						//2、修改Sell状态为2交易成功
						Sell sell = match.getSell();
						sell.setStatus(2);
						sellDAO.merge(sell);
						
						//最后操作时间(72小时)
						RegisterUser sellUser = registerUserDAO.findUniqueBy("loginName", sell.getSellUser());
						Calendar cl = new GregorianCalendar();
						cl.setTime(new Date());
						cl.set( Calendar.DATE, cl.get( Calendar.DATE )+3);
						sellUser.setLastOptTime(cl.getTime());
						sellUser.setTempTime(sellUser.getLastOptTime());
						registerUserDAO.merge(sellUser);
					}
					
					//3、判断是否首单及处理
					RegisterUser registerUser = registerUserDAO.findUniqueBy("loginName", buy.getBuyUser());
					if(registerUser.getRegisterMoney()==0){
						registerUser.setRegisterMoney(buy.getBuyMoney());
						registerUserDAO.merge(registerUser);
						
						//首单额外奖：
						System.out.println("----计算首单额外奖------");
						firstSingleBonus(buy);
						
						System.out.println("----计算对碰奖------");
						//小组提成（对碰奖）
						bonusService.dpAward(ruleDTO , buy.getBuyMoney() , registerUser , registerUser);
					}
					
					System.out.println("----计算领导奖------");
					//领导奖
					RegisterUser recommerUser = registerUserDAO.findUniqueBy("loginName", registerUser.getRecommendUser());
					if(recommerUser!=null){
						bonusService.algebraicAward(ruleDTO,registerUser,recommerUser,buy.getBuyMoney(),0);
					}
					
				}	
				match.setCalculated(true);
				matchDAO.merge(match);
			}
		}
	}
	
	private boolean isAllMatchConfirm(Buy buy){
		MatchQueryDTO queryDTO = new MatchQueryDTO();
		queryDTO.setStart(0);
		queryDTO.setLimit(100);
		queryDTO.setStatus(2);
		queryDTO.setBuyId(buy.getId());
		PageDTO pageDTO = matchDAO.findMatchPage(queryDTO, null, null);
		
		if(pageDTO.getTotalSize()>0){
			List<Match> lists = (List<Match>)pageDTO.getData();
			Long total = 0L;
			for(Match match : lists){
				total =total+match.getMatchMoney();
			}
			if(total > 0 && total.equals(buy.getBuyMoney())){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
	
	private boolean isAllMatchConfirm(Sell sell){
		MatchQueryDTO queryDTO = new MatchQueryDTO();
		queryDTO.setStart(0);
		queryDTO.setLimit(100);
		queryDTO.setStatus(2);
		queryDTO.setSellId(sell.getId());
		PageDTO pageDTO = matchDAO.findMatchPage(queryDTO, null, null);
		
		if(pageDTO.getTotalSize()>0){
			List<Match> lists = (List<Match>)pageDTO.getData();
			Long total = 0L;
			for(Match match : lists){
				total =total+match.getMatchMoney();
			}
			if(total > 0 && total.equals(sell.getSellMoney())){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
	
	
	//首单额外奖
	private void firstSingleBonus(Buy buy){
		//首单额外奖：
		//1万--100，2万--200，3W--500，4万--800，5万—1000
		Long bonus = 0L;
		if(buy.getBuyMoney()>=10000){
			bonus = 100L;
		}
		if(buy.getBuyMoney()>=20000){
			bonus = 300L;		
		}
		if(buy.getBuyMoney()>=30000){
			bonus = 500L;
		}
		if(buy.getBuyMoney()>=40000){
			bonus = 800L;
		}
		if(buy.getBuyMoney()>=50000){
			bonus = 1000L;
		}
		if(bonus>0){
			TransactionRecord t = new TransactionRecord();
			t.setLoginName(buy.getBuyUser());
			t.setTransactionObject("system");
			t.setTransactionType(TranType.FirstSingleBonus);
			t.setRemark("首单额外奖");
			transactionRecordService.updateTran(t, TranType.DYNAMIC, bonus.doubleValue(), TranType.ADD);
			System.out.println("--------<<拿到计算首单额外奖>>-----"+bonus);
		}
		
	}
	/**
	 * 超时未付款
	 * 48小时间未汇款流程
	 * 1、冻结汇款方账号
	 * 2、未收到汇款的金额重新匹配
	 */
	@Transactional
	public String timeoutPay(){
		StringBuffer sb = new StringBuffer();
		sb.append(">>>>>>>>>>>>>48小时未汇款检查\r\n");
		List<Match> lists = matchDAO.findTimeOutMatch(48, new Integer[]{0},"createTime");
		if(lists!=null && lists.size()>0){
			for(Match entity : lists){
				sb.append("超过48小时未汇款账号："+entity.getBuy().getBuyUser()+"，将对其冻结!\r\n");
				RegisterUser registerUser = registerUserDAO.findUniqueBy("loginName", entity.getBuy().getBuyUser());
				registerUser.setUserStatus("1");
				registerUserDAO.merge(registerUser);
			}
		}else{
			sb.append("-------未发现48小时未汇款的记录------------------------\r\n");
		}
		return sb.toString();
	}
	
	
	/**
	 * 超时未确认(自动确认)
	 */
	public String timeoutConfirm(){
		StringBuffer sb = new StringBuffer();
		sb.append(">>>>>>>>>>>>>48小时未确认汇款检查------------------------\r\n");
		List<Match> lists = matchDAO.findTimeOutMatch(48, new Integer[]{1},"messageTime");
		if(lists!=null && lists.size()>0){
			for(Match entity : lists){
				sb.append("超过48小时未确认汇款账号："+entity.getBuy().getBuyUser()+"，将对其自动确认!\r\n");
//				RegisterUser registerUser = registerUserDAO.findUniqueBy("loginName", entity.getBuy().getBuyUser());
//				registerUser.setUserStatus("1");
//				registerUserDAO.merge(registerUser);
				MatchDTO matchDTO = new MatchDTO();
				matchDTO.setId(entity.getId());
				matchDTO.setConfirmType("48小时自动确认");
				confirmPay(matchDTO);
				checkCompute();
			}
		}else{
			sb.append("-------未发现48小时未确认汇款的记录------------------------\r\n");
		}
		return sb.toString();
	}
	
	/**
	 * 取消
	 * @param matchId
	 * @return
	 */
	@Transactional
	public void cleanMatch(Long matchId){
		Match match = matchDAO.findById(matchId);
		
		//更新状态
		match.setStatus(6);
		matchDAO.merge(match);
		
		//退回买入/卖出
		Buy buy = match.getBuy();
		buy.setSurplusMoney(buy.getSurplusMoney()+match.getMatchMoney());
		buyDAO.merge(buy);
		
		Sell sell = match.getSell();
		sell.setSurplusMoney(sell.getSurplusMoney()+match.getMatchMoney());
		sellDAO.merge(sell);

	}
	
	/**
	 * 未收到款项
	 * @param matchId
	 */
	@Transactional
	public synchronized String notReceive(Long matchId){
		Match match = matchDAO.findById(matchId);
		if(match.getStatus().equals(1)){
			match.setStatus(3);
			matchDAO.merge(match);
			return "操作成功!";
		}else{
			return "操作失败!";
		}
	}
	
	/**
	 * 账号检查
	 * 72小时不操作冻结
	 */
	@Transactional
	public String accoutCheck(){
		StringBuffer sb = new StringBuffer();
		sb.append(">>>>>>>>>>>>>72小时未操作检查开始------------------------\r\n");
		RegisterUserQueryDTO queryDTO = new RegisterUserQueryDTO();
		queryDTO.setLastOptTime(new Date());
		queryDTO.setLimit(100);
		PageDTO pageDTO = registerUserDAO.findPager(queryDTO, null, null);
		List<RegisterUser> registerUsers = (List<RegisterUser>) pageDTO.getData();
		String[] strs = new String[]{"258145325@qq.com"};
		for(RegisterUser registerUser : registerUsers){
			if(!isIn(registerUser.getLoginName(),strs)){
				sb.append("--72小时未操作冻结账号"+registerUser.getLoginName()+"\r\n");
				registerUser.setUserStatus("1");
				registerUserDAO.merge(registerUser);
			}
			
		}
		sb.append(">>>>>>>>>>>>>72小时未操作检查结束------------------------\r\n");
		return sb.toString();
	}
	
	public boolean isIn( String str,String[] strs )
    {
        boolean result = false;

        for ( int i = 0; i < strs.length; i++ )
        {
            if ( str.endsWith( strs[i] ) || str.equals(strs[i]) )
            {
                result = true;
            }
        }
        return result;
    }
	
	@Transactional
	public void autoCheck(){
		StringBuffer sb = new StringBuffer();
		sb.append(timeoutPay());
		sb.append(timeoutConfirm());
		sb.append(accoutCheck());
		logger.error(sb.toString());
	}
	
	/**
	 * 对大于2的卖出股进行拆分
	 * @return
	 */
	@Transactional
	public String sellSplit(){
		//全部等待拆分的记录
		SellQueryDTO queryDto = new SellQueryDTO();
		queryDto.setSearchType("Split");
		queryDto.setLimit(100000);
		List<Sell> sells = sellDAO.findSellPage(queryDto, null, null).getData();
		StringBuffer sb = new StringBuffer();
		
		Long before = 0L;
		Long back = 0L;
		
		sb.append("-----正在对大于0.2的卖出股进行拆分-----\r\n<br>");
		for(Sell sell : sells){
			sb.append("-----正在对-----"+sell.getUser()+",股数:"+sell.getSurplusMoney()+",股价:"+sell.getSellPrice()+"-进行拆分\r\n<br>");
			before=before+sell.getSurplusMoney();
			sell.setSellMoney(sell.getSellMoney()*2);
			sell.setSurplusMoney(sell.getSurplusMoney()*2);
			sell.setSellPrice(DoubleFormat.format(sell.getSellPrice()/2));
			sell.setSplitQuy(sell.getSplitQuy()+1);//拆分次数
			sell.setSplitedGuShu(sell.getSurplusMoney());//拆分后股数
			back=back+sell.getSurplusMoney();
			sellDAO.merge(sell);
		}
		sb.append("-----拆分前股数:"+before+"-----\r\n<br>");
		sb.append("-----拆分后股数:"+back+"-----\r\n<br>");
		sb.append("-----对大于0.2的卖出股进行拆分已结束-----\r\n<br>");
		
		RuleDTO ruleDTO = ruleService.findRuleInfo();
		Rule rule = ruleDAO.findById(ruleDTO.getRuleId());
		rule.setRule038(rule.getRule038()+1);
		return sb.toString();
	}
	
	@Transactional
	public CurrentSaleDTO getCurrentSale(){
		CurrentSaleDTO dto = new CurrentSaleDTO();
		
		
		//上次收盘价
		Double result2 = 0D;
		RuleDTO ruleDTO = ruleService.findRuleInfo();
		if(ruleDTO.getClosingPrice()!=null){
			result2 = ruleDTO.getClosingPrice();
		}
		dto.setMarketStatus(ruleDTO.getMarketStatus());
		dto.setClosingPrice(result2);
		
		//今日成交股
		Long result1 = 0L;
		try {
			List<Object> objs = sellDAO.todayAllSell();
			for(Object obj : objs){
				result1 = (Long)obj;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		if(result1==null){
			result1=0L;
		}
		dto.setTodayClinchShare(result1.doubleValue());
		
		//今日成交额
		Double result = 0D;
		try {
			List<Object> objs = sellDAO.todayAllBuy();
			
			for(Object obj : objs){
				result = (Double)obj;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		if(result==null){
			result=0D;
		}
		dto.setTodayClinchMoney(result);
		
		//当前股价
		Sell sell = sellDAO.findTop1SellOrder();
		if(sell!=null){
			if(sell.getSellPrice()>0.2){
				dto.setCurrentPrice(0.2D);
			}else{
				dto.setCurrentPrice(sell.getSellPrice());
			}
			
		}
		return dto;
	}
	
}
